﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using SpecFlowTfsConnector;
using SpecFlowTfsLinker.Entities;

namespace SpecFlowTfsLinkerAddIn
{
    public class UserStorySelectorModel : INotifyPropertyChanged
    {
        public TfsSpecFlowConnector Connector { get; private set; }

        public UserStorySelectorModel(TfsSpecFlowConnector specFlowConnector)
        {
            Connector = specFlowConnector;
        }

        public IEnumerable<string> Projects
        {
            get
            {
                try
                {
                    return from Project project in Connector.Connector.GetProjects() select project.Name;
                }
                catch (Exception ex)
                {
                    var box =new UserStorySelectorException(ex);
                    box.ShowDialog();
                    return new List<string>();
                }

            }
        }

        private string _SelectedProject;
        public string SelectedProject
        {
            get { return _SelectedProject; }
            set
            {
                _SelectedProject = value;
                NotifyPropertyChanged("UserStories");
            }
        }

        public List<UserStory> UserStories
        {
            get
            {
                if (!string.IsNullOrEmpty(SelectedProject))
                    return Connector.GetUserStories(SelectedProject);
                return new List<UserStory>();
            }
        }

        public ICollectionView UserStoriesCollection
        {
            get { return CollectionViewSource.GetDefaultView(UserStories); }
        }

        public UserStory SelectedUserStory { get; set; }

        private ICollectionView _filteredView;

        public ICollectionView Filteredview
        {
            get { return _filteredView; }
            set
            {
                if (value != _filteredView)
                {
                    _filteredView = value;
                    NotifyPropertyChanged("Filteredview");
                }
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        private void NotifyPropertyChanged(string info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}